package com.bojx.report.controller;

import java.io.File;
import java.sql.BatchUpdateException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.bojx.report.pojo.Result;
import com.bojx.report.service.ExcelService;
import com.bojx.report.service.ExcelUploadService;
import com.bojx.report.service.QuarterExcelService;
import com.bojx.report.service.QueryService;
import com.bojx.report.util.ResultUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

public class IndexController extends Controller {
	private static Logger LOG = Logger.getLogger(IndexController.class);
	private ExcelService excelService = new ExcelService();
	private QuarterExcelService quarterExcelService = new QuarterExcelService();
	private QueryService queryService = new QueryService();

	public void index() {
		render("index.html");
	}

	/**
	 * 上传月报页面
	 */
	public void uploadData() {
		List<Record> banks = Db.find("select * from report_bank_data");
		setAttr("banks", banks);
		render("upload.html");
	}

	/**
	 * 上传季报页面
	 */
	public void uploadQuarterReport() {
		List<Record> banks = Db.find("select * from report_bank_data");
		setAttr("banks", banks);
		render("uploadQuarterReport.html");
	}

	/**
	 * 上传月报表
	 */
	public void dataUpdate() {
		@SuppressWarnings("rawtypes")
		Result result = null;
		UploadFile uploadFile = getFile("file");
		String organization = getPara("organization");
		Integer year = getParaToInt("year");
		Integer month = getParaToInt("month");
		try {
			ExcelService service = enhance(ExcelService.class);
			Map<String, Object> rsp = service.analyze(uploadFile, organization, year, month);
			result = ResultUtil.success(rsp);
		} catch (BatchUpdateException e1) {
			LOG.error(e1.getMessage(), e1);
			result = ResultUtil.error("10", "请勿重复提交");
		} catch (Exception e2) {
			LOG.error(e2.getMessage(), e2);
			result = ResultUtil.error("10", e2.getMessage());
		}
		render(new JsonRender(result).forIE());
	}

	/***
	 * 上传季报表
	 */
	@SuppressWarnings("rawtypes")
	public void addQuarterReport() throws BatchUpdateException {
		Result result = null;
		UploadFile uploadFile = getFile("file");
		String bank = getPara("bank");
		Integer year = getParaToInt("year");
		Integer quarter = getParaToInt("quarter");
		try {
			ExcelUploadService service = enhance(ExcelUploadService.class);
			service.addQuarterReport(uploadFile, bank, year, quarter);
			result = ResultUtil.success();
		} catch (Exception e2) {
			LOG.error(e2.getMessage(), e2);
			result = ResultUtil.error("10", e2.getMessage());
		}
		render(new JsonRender(result).forIE());
	}

	public void monthReport() {
		render("monthReport.html");
	}

	// 生成月报表
	public void produceReport() {
		@SuppressWarnings("rawtypes")
		Result result = null;
		try {
			int year = getParaToInt("year");
			int month = getParaToInt("month");
			String fileName = excelService.generate(year, month);
			result = ResultUtil.success(fileName);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result = ResultUtil.success(e.getMessage());
		}
		render(new JsonRender(result).forIE());
	}

	public void download() {
		String fileName = getPara("fileName");
		PropKit.use("appconfig.properties", "UTF-8");
		String reportFolder = PropKit.get("reportFolder");
		renderFile(new File(reportFolder + "/" + fileName));
	}

	// 生成季报页面
	public void quarterlyReport() {
		render("quarterlyReport.html");
	}

	// 生成季报表
	public void produceQuarterReport() {
		@SuppressWarnings("rawtypes")
		Result result = null;
		try {
			int year = getParaToInt("year");
			int quarter = getParaToInt("quarter");
			String fileName = quarterExcelService.generateQuarterReport(year, quarter);
			result = ResultUtil.success(fileName);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result = ResultUtil.success(e.getMessage());
		}
		render(new JsonRender(result).forIE());
	}

	// 生成季报（累计）页面
	public void quarterlyAddReport() {
		render("quarterlyAddReport.html");
	}

	// 生成季报表(累计)
	public void produceQuarterAddReport() {
		@SuppressWarnings("rawtypes")
		Result result = null;
		try {
			int year = getParaToInt("year");
			int quarter = getParaToInt("quarter");
			String fileName = quarterExcelService.generateQuarterAddReport(year, quarter);
			result = ResultUtil.success(fileName);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result = ResultUtil.success(e.getMessage());
		}
		render(new JsonRender(result).forIE());
	}

	/**
	 * 已经上传的月报表
	 */
	public void uploadedReport() {
		render("uploadedReport.html");
	}

	public void excelData() {
		int pageNum = getParaToInt("page", 1);
		pageNum = pageNum > 0 ? pageNum : 1;
		int rows = getParaToInt("rows", 30);
		String organization = getPara("organization");
		String year = getPara("year");
		String month = getPara("month");
		Kv kv = Kv.by("pageNum", pageNum).set("rows", rows).set("organization", organization).set("year", year)
				.set("month", month);
		Page<Record> page = queryService.queryExcelData(kv);
		setAttrs(buildPagination(page.getList(), page.getTotalRow()));
		render(new JsonRender().forIE());
	}

	public void bankDataDetail() {
		try {
			Long id = getParaToLong("id");
			Record uploadedExcelRecord = Db.findById("report_uploaded_excel", id);
			String bankName = uploadedExcelRecord.getStr("bank");
			int year = uploadedExcelRecord.getInt("year");
			int month = uploadedExcelRecord.getInt("month");
			Record data = queryService.queryData(bankName, year, month);
			setAttr("data", data);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		render("detail.html");
	}

	@Before(Tx.class)
	public void dataDel() {
		@SuppressWarnings("rawtypes")
		Result result = null;
		try {
			Long id = getParaToLong("id");
			Record uploadExcelRecord = Db.findById("report_uploaded_excel", id);
			int year = uploadExcelRecord.getInt("year");
			int month = uploadExcelRecord.getInt("month");
			String bank = uploadExcelRecord.getStr("bank");
			Db.update("delete from report_bank_branch_data where organization=? and year=? and month=?", bank, year,
					month);
			Db.update("delete from report_client_data where organization=? and year=? and month=?", bank, year, month);
			Db.update("delete from report_business_data where organization=? and year=? and month=?", bank, year,
					month);
			Db.deleteById("report_uploaded_excel", id);
			result = ResultUtil.success();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result = ResultUtil.success(e.getMessage());
			try {
				DbKit.getConfig().getThreadLocalConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		render(new JsonRender(result).forIE());
	}

	/***
	 * 已经上传的季报表
	 */
	public void uploadedQuarterReport() {
		render("uploadedQuarterReport.html");
	}

	public void quarterExcelData() {
		int pageNum = getParaToInt("page", 1);
		pageNum = pageNum > 0 ? pageNum : 1;
		int rows = getParaToInt("rows", 30);
		String bank = getPara("bank");
		String year = getPara("year");
		String quarter = getPara("quarter");
		Kv kv = Kv.by("pageNum", pageNum).set("rows", rows).set("bank", bank).set("year", year).set("quarter", quarter);
		Page<Record> page = queryService.queryQuarterExcelData(kv);
		setAttrs(buildPagination(page.getList(), page.getTotalRow()));
		render(new JsonRender().forIE());
	}

	public void quarterBankDataDetail() {
		try {
			Long id = getParaToLong("id");
			Record uploadedExcelRecord = Db.findById("report_quarter_uploaded_excel", id);
			String bankName = uploadedExcelRecord.getStr("bank");
			int year = uploadedExcelRecord.getInt("year");
			int quarter = uploadedExcelRecord.getInt("quarter");
			List<List<Object>> data = queryService.queryQuarterData(bankName, year, quarter);
			setAttr("data", data);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		render("quarterDetail.html");
	}

	@SuppressWarnings("rawtypes")
	@Before(Tx.class)
	public void quarterDataDel() {
		Result result = null;
		try {
			Long id = getParaToLong("id");
			Record uploadExcelRecord = Db.findById("report_quarter_uploaded_excel", id);
			int year = uploadExcelRecord.getInt("year");
			int quarter = uploadExcelRecord.getInt("quarter");
			String bank = uploadExcelRecord.getStr("bank");
			Db.update("delete from report_quarter_bank_branch_data where bank=? and year=? and quarter=?", bank, year,
					quarter);
			Db.update("delete from report_quarter_client_data where bank=? and year=? and quarter=?", bank, year,
					quarter);
			Db.update("delete from report_quarter_business_data where bank=? and year=? and quarter=?", bank, year,
					quarter);
			Db.deleteById("report_quarter_uploaded_excel", id);
			result = ResultUtil.success();
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			result = ResultUtil.success(e.getMessage());
			try {
				DbKit.getConfig().getThreadLocalConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		render(new JsonRender(result).forIE());
	}

	// ------------------------------------本地方法----------------------------------------------
	@SuppressWarnings("rawtypes")
	protected Map<String, Object> buildPagination(List list, Integer count) {
		return buildPagination(list, count, null);

	}

	@SuppressWarnings("rawtypes")
	protected Map<String, Object> buildPagination(List list, Integer count, List<Map<String, Object>> footer) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", count);
		map.put("rows", list);
		if (footer != null)
			map.put("footer", footer);
		return map;
	}
}
